package com.junke.question.service.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.junke.question.service.common.Response;
import org.apache.http.protocol.RequestDate;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * 认证失败过滤
 */
@Component
public class LoginFailureFilter implements AuthenticationFailureHandler {
    private Response respBean;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Response respBean;
        if (e instanceof LockedException){
            respBean= Response.failed("账户被锁定，登录失败！");
        }else if (e instanceof BadCredentialsException){
            respBean= Response.failed("账户名或密码输入错误，请重新输入！");
        }else if (e instanceof DisabledException){
            respBean= Response.failed("账户被禁用，登录失败！");
        }else if (e instanceof AccountExpiredException){
            respBean= Response.failed("账户已过期，登录失败！");
        }else if (e instanceof CredentialsExpiredException){
            respBean= Response.failed("密码已过期，登录失败！");
        }else {
            respBean= Response.failed("登录失败！");
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(respBean);

        writer.write(s);
        writer.flush();
        writer.close();

    }
}
